package cn.com.callback

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.elite.EliteBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.Util;
import org.json.JSONObject;
import org.json.JSONArray
import org.json.JSONException;
import java.text.SimpleDateFormat;

/**
 *
 * @Title: api_SZWaterDBresult
 * @Description: 功能介绍：定时调用此接口，将documentout中发送的短信，调度短信平台接口获取结果
 * @author: chieh
 * @date 2021-11-22 15:28:00
 *
 */

public class api_SZWaterDBresult implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(api_SZWaterDBresult.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response){

		try{
			def SMSCount = 0;
			def msg;
			def message;
			def outdata;
			def updateDocumentoutSQL;
			
			log.debug("捞取短信开始执行------------------------------");
				def selectDocumentoutSQL = "select top 1000 documentout_guid,Documentto,resultCode from Documentout where 1=1 and Passflag = '1' and  (Result is null  or Result='') and resultCode is not null and Expectedstartdate >= Getdate()-1 And TRIALCOUNT < TRIALCOUNTLIMIT And (Dateadd(Ss, 30 * TRIALCOUNT, Finishdatetime) < Getdate() Or Finishdatetime Is Null Or Finishdatetime = '') and createtime < '' order by case when STRINGFIELD1='人工短信' then 1  when STRINGFIELD1='工单' then 2 when STRINGFIELD1='工单催单短信' then 2 when STRINGFIELD1='通讯录短信' then 3 when STRINGFIELD1='智慧停水发送' then 4 when STRINGFIELD1='人工批次发送' then 4 end,TRIALCOUNT asc";
				log.debug("查询待捞取短信selectDocumentoutSQL="+selectDocumentoutSQL);

				List selectDocumentoutList = eliteBean.chaxun_sql(selectDocumentoutSQL, "dataSource");
				def ListNum = selectDocumentoutList.size();
				log.debug("待捞取短信数量ListNum=" + ListNum);

				if(ListNum > 0){
					
					def pageSize = "100";
					double number=ListNum*1.0/Integer.parseInt(pageSize);
					log.debug("number :" + number);
					//提交缓存次数取整
					int count=Math.ceil(number);
					log.debug("count :" + count);
					int yscount=ListNum%Integer.parseInt(pageSize);
					log.debug("yscount :" + yscount);
					
					int datacount=0;
					//判断data长度,根据实际情况重置申明
					if(count==1) {
						datacount=yscount;
					}else {
						datacount=100;
					}
					//默认申明100条,用于list批次提交缓存
					String[] data=new String[datacount];
					
					//累计数 m 提交缓存累计数、 n提交缓存批次数
					int m = 0,n =0;
					for(int i= 0; i<ListNum; i++) {
						Map selectDocumentoutSQLMap = selectDocumentoutList.get(i);

						def documentout_guid = selectDocumentoutSQLMap.get("Documentout_Guid");
						def Documentto = selectDocumentoutSQLMap.get("Documentto");//手机号码
						def resultCode = selectDocumentoutSQLMap.get("resultCode");//结果code
						
						outdata=obtainsms(resultCode);
						log.debug("outdata："+outdata);
						//解析返回信息
						JSONObject jsonObject = new JSONObject(outdata);
						String statusCode = GetJV(jsonObject, "statusCode");
						
						String resultList = GetJV(jsonObject, "resultList");
						log.debug("statusCode："+statusCode);
						if(statusCode=="0") {
							SMSCount++;
							
							JSONArray arrJsonArray = new JSONArray(resultList);
							int arrInt = arrJsonArray.length();
							log.debug("接入List数量:" + arrInt);
							
							String status,returnTime,submitId,mobile="";
							for (int j = 0; j < arrInt; j++) {
								JSONObject arrCustJson = arrJsonArray.getJSONObject(j);

								//获取案件信息
								status = GetJV(arrCustJson, "status");//短信状态码
								returnTime = GetJV(arrCustJson, "returnTime");//短信返回时间
								submitId = GetJV(arrCustJson, "submitId");//提交id
								mobile = GetJV(arrCustJson, "mobile");//手机号
							}
							//异常保护 为获取到默认是空的
							if(arrInt==0){
								status="";
								SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
								returnTime=df.format(new Date());
								log.debug("returnTime:" + returnTime);
							}
							data[m]  = "Update Documentout Set Result = '" + status + "',Finishdatetime=case when '" + returnTime + "'='' then null else '" + returnTime + "' end,TRIALCOUNT = TRIALCOUNT + 1  Where Documentout_Guid = '" + documentout_guid + "' and resultCode= '" + resultCode + "'";
							
						}else {
							log.debug("短信结果捞取接口失败！");
						}
						//累计
						m++;
						//一批update 100条,或是最后余下的批次数量
						if(m==100||(count==n+1&&m==yscount)){
							//批量更新短信发送结果
							log.debug("批量更新短信结果处理SQL:" + data.toString());
							int[] dataresult = eliteBean.updateBatch(data, "dataSource");
							log.debug("批量更新短信结果处理SQL结果:" + dataresult.toString());
							//判断data长度,根据实际情况重置申明
							if(count==n+2) {
								datacount=yscount;
							}else {
								datacount=100;
							}
							data=new String[datacount];
							m=0;
							//累计提交次数
							n++;
						}
						
					}
					msg = "当前批次共有" + ListNum + "条数据，成功捞取" + SMSCount + "条！";
					log.debug("当前需要捞取短信的处理结果:" + msg);
					message = "{\"message\":\"" + msg + "\"}";
					
				}else {
					message = "{\"message\":\"当前批次下没有需要捞取结果的短信\"}";
				}

			
		}catch(Exception e){
			log.error("result异常信息：" ,e);
		}
	}
	
	//短信发送接口
	public static String obtainsms(String resultCode) {

		long startTime = System.currentTimeMillis();
		log.debug("处理开始时间:" + startTime);

		long endTime = System.currentTimeMillis();

		String reJson = null;
		try {

			//String doURL = getProperty.get("HSTURL");
			String doURL = "http://138.0.0.53:8083/sms/api/report";
			log.debug("doURL:" + doURL);
			
			String userId="CRMAPI";
			String password="ghbsmsapi";
			String apikey="89a47d";
			String signafter="";
			String sign="";
			
			//加盐pwd= md5(userId + 明文密码 + 盐
			signafter=userId+password+apikey;
			log.debug("1加密前:"+signafter);
			signafter=Util.getMD5Str(signafter);
			log.debug("1加密后:"+signafter);
			//MD5(userId+pwd)
			signafter=userId+signafter;
			log.debug("2加密前:"+signafter);
			sign=Util.getMD5Str(signafter);
			log.debug("2加密后:"+sign);

			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/json");
			String injson ="{\"userId\": \""+userId+"\",\"signature\": \""+sign+"\",\"submitIdList\":[ \""+resultCode+"\"]}";
			log.debug(injson);
			def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
			log.debug("getResult:" + getResult);
			
			reJson=getResult;
			
		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			reJson = "{\"statusCode\":\"-1\",\"resultMsg\":捞取短信结果接口异常\",\"resultList\":[]}";
		}

		return reJson;
	}
	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		log.debug("解析-k=" + getKey + " v=" + Rev_Value);
		return Rev_Value;
	}
}